<?php
namespace app\common\model;
use app\common\lib\Org\Util\ChuanglanSmsApi;
use think\exception\HttpException;

class Sms
{
    /**
     * 发送验证码
     * @param $key
     * @param $phoneNumber
     * @param $msg
     * @return bool
     * @throws \Exception
     */

    static public function send($key,$phoneNumber,$msg){
        if(empty($phoneNumber)){
            throw new HttpException(200,'手机号不能为空');
        }
        $redis=new Redis();
//        if($redis->exists($key)){
//            $ret['result']=0;
//            $ret['msg']='请不要频繁获取验证码！';
//            return $ret;
//        }
        $random = rand(10000, 99999);
        $ttl=config('sms_ttl'); //500秒
        $tipTime=intval($ttl/60);
        $content = $msg." 验证码：{$random}，{$tipTime}分钟内有效。";
        $Sms = new ChuanglanSmsApi();
        $result = $Sms->sendSMS($phoneNumber,$content);
        $result = $Sms->execResult($result);
        if( $result[1] == 0 ){
            $redis->set($key,$random,$ttl);
            $ret['result']=1;
            $ret['msg']='发送成功';
            return $ret;
        }else{
            $ret['result']=0;
            $ret['msg']='短信接口故障';
            return $ret;
        }
    }

    /**
     * 验证短信验证码
     * 参数:键名,验证码
     * 验证成功返回操作token,失败false
     */
    static public function verify($key,$code){
        $redis=new Redis();
        $savedCode=$redis->get($key);
        if(!empty($code)&&(string)$savedCode===(string)$code){
            $random = rand(10000000, 99999999);
            $redis->set($key,$random,config('action_code_ttl'));
            return $random;
        }else{
            return false;
        }
    }


    /**
     * 2次验证
     * 参数:键名,验证码
     * 验证成功返回操作token,失败false
     */
    static public function verify2($key,$code){
        $redis=new Redis();
        $savedCode=$redis->get($key);
        if(!empty($code)&&(string)$savedCode===(string)$code){
            $redis->delete($key);
            return true;
        }else{
            return false;
        }
    }


}



